var UploadCrop = {
    is_defined: function (_obj) {
        return "undefined" == typeof(_obj) ? false : _obj;
    },
    file_blur: function () {
        $("#fileuploadButton").blur();
    },
    reset_form: function () {
        $("#myupload").get(0).reset();
    },
    init: function (_opt, _arg) {
        var containerWidth = _opt.cropMaxWidth + 100;
        var containerHeight = _opt.cropMaxHeight + 50;
        this.diag = new Dialog();
        this.diag.ID="updateImage";
        this.diag.Width = _opt.cropMaxWidth + containerWidth + 35;
        this.diag.Height = containerHeight + 50;
        this.diag.Left = "50%";
        this.diag.Top = "50%";
        this.diag.Title = "图片处理";
        this.diag.CancelEvent = function () {
            delete_image(2);
            UploadCrop.diag.close();
        };
        //框架的HTML代码
        var div = "<div class=\"mainDiv\" id=\"mainDiv\" style=\"width:" + (this.diag.Width + 2) + "px;height:" + this.diag.Height + "px\">";
        div += "<div class=\"topDiv\">";
        div += "<div class=\"btn\">";
        div += "<span>上传图片</span><input id=\"fileuploadButton\" type=\"file\" name=\"mypic\" />";
        div += "</div>";
        div += "<div class=\"progress\">";
        div += "<span class=\"bar\"></span><span class=\"percent\">0%</span>";
        div += "</div>";
        div += "<div class=\"msgDiv\">";
        div += "<div class=\"files\"></div>";
        div += "<div id=\"showimg\"></div>";
        div += "</div>";
        div += "</div>";
        div += "<div class=\"bottomDiv\">";
        div += "<div class=\"boxes\">";
        div += "<div id=\"crop_container\" style=\"width: " + containerWidth + "px; height: " + containerHeight + "px; background-color: rgb(204, 204, 204); overflow: hidden; position: relative; border: 2px solid rgb(51, 51, 51);\"></div>";
        div += "<div class=\"result\" style=\"width: " + _opt.cropMaxWidth + "px; height: " + _opt.cropMaxHeight + "px\">";
        div += "<div class=\"txt\" style=\"text-align: center;\">裁切后的图片</div>";
        div += "</div>";
        div += "<div style=\"width: " + _opt.cropMaxWidth + "px; height: 40px; float: right; text-align: center;\">";
        div += "<span class=\"button-wrapper\" style=\"margin: 15px auto;width:45px\">";
        div += "<span class=\"l\"></span><span class=\"r\"></span><a class=\"button\" href=\"javascript:void(0)\" id=\"cropButton\">裁切</a>";
        div += "</span>&nbsp;";
        div += "<span class=\"button-wrapper\" style=\"margin: 15px auto;width:45px\">";
        div += "<span class=\"l\"></span><span class=\"r\"> </span> <a class=\"button\" href=\"javascript:void(0)\" id=\"restoreButton\">复位</a>";
        div += "</span>&nbsp;";
        div += "<span class=\"button-wrapper\" style=\"margin: 15px auto;width:45px\">";
        div += "<span class=\"l\"> </span><span class=\"r\"></span><a class=\"button\" href=\"javascript:void(0)\" id=\"completeButton\">确定</a>";
        div += "</span>";
        div += "</div>";
        div += "<div class=\"cleared\"></div>";
        div += "</div>";
        div += "</div>";
        div += "</div>";
        this.diag.InnerHtml = div;
        this.diag.show();
        $("#completeButton").attr("data-save", _arg);
        /**
         * 判断有无初始图片
         */
        if (this.is_defined(_opt.srcImage)) {
            this.srcImage = this.is_defined(_opt.srcImage);
            this.srcImageUrl = _opt.imageUrl + _opt.srcImage + "?t=" + (new Date()).getTime();//避免缓存
            imgReady(this.srcImageUrl, function () {
                UploadCrop.imgW = this.width;
                UploadCrop.imgH = this.height;
                UploadCrop.cropzoom = $('#crop_container').cropzoom({
                    width: containerWidth,//显示原始图片容器的宽度
                    height: containerHeight,//显示原始图片容器的高度
                    bgColor: '#CCC',
                    enableRotation: true,
                    enableZoom: true,
                    zoomSteps: 1,
                    rotationSteps: 90,
                    selector: {
                        w: _opt.cropMinWidth,
                        h: _opt.cropMinHeight,
                        maxWidth: _opt.cropMaxWidth,
                        maxHeight: _opt.cropMaxHeight,
                        centered: true,
                        borderColor: 'blue',
                        borderColorHover: 'red'
                    },
                    image: {
                        source: UploadCrop.srcImageUrl,
                        width: UploadCrop.imgW,
                        height: UploadCrop.imgH,
                        minZoom: 50,
                        maxZoom: 300,
                        startZoom: 100
                    }
                });
                UploadCrop.cropzoom.setSelector(0, 0, _opt.cropMaxWidth, _opt.cropMaxHeight, true);
                $("#crop_container_selector").css("position", "absolute");
                $("#saveLastImgInfo").val(UploadCrop.srcImage);
                btn.html("上传图片");
                $(".result").find("img").remove();
                $("#myupload")[0].reset();
            });
        }
        /**
         * 初始化调用对象
         */
        var bar = $('.bar');
        var percent = $('.percent');
        var showimg = $('#showimg');
        var progress = $(".progress");
        var files = $(".files");
        var btn = $(".btn span");
        /**
         * 创建两个隐藏域,用于保存上一次上传的图片信息和上一次裁切的图片信息
         */
        $("#saveLastImgInfo,#saveLastCropImgInfo").remove();
        $("body").append("<input type=\"hidden\" id=\"saveLastImgInfo\" value=\"\" /><input type=\"hidden\" id=\"saveLastCropImgInfo\" value=\"\" />");
        /**
         * 双击裁切事件
         */
        $("#crop_container_selector").dblclick(function () {
            $("#cropButton").trigger("click");
        });
        /**
         * 裁切按钮点击事件
         */
        $("#cropButton").click(function () {
            var last_img = $("#saveLastImgInfo").val();
            if (0 == $("#k").find("image").length) {
                alert("请选择要上传的图片！！");
                return;
            }
            UploadCrop.cropzoom.send(_opt.postUrl, 'POST', {
                act: "crop",
                imageSource: last_img
            }, function (last_crop_img) {
                $('.result').find('img').remove();
                var img = $('<img />').attr('src', _opt.imageUrl + "/" + last_crop_img + "?t=" + (new Date()).getTime());
                $('.result').find('.txt').hide().end().append(img);
                $("#saveLastCropImgInfo").val(last_crop_img);
            });
        });
        /**
         * 复位按钮点击事件
         */
        $("#restoreButton").click(function () {
            if (0 == $("#k").find("image").length) {
                alert("请选择要上传的图片！！");
                return;
            }
            delete_image(1);
            $("#myupload")[0].reset();
            $('.result').find('img').remove();
            $('.result').find('.txt').show();
            UploadCrop.cropzoom.restore();
        });
        /**
         * 删除链接点击事件
         */
        $("#delimgButton").click(function () {
            var last_img = $("#saveLastImgInfo").val();
            var last_crop_img = $("#saveLastCropImgInfo").val();
            $.post(_opt.postUrl, {
                act: "delete",
                last_img: last_img,
                last_crop_img: last_crop_img
            }, function (data) {
                if ("1" == data) {
                    files.html("删除成功.");
                    showimg.empty();
                    //重置表单事件(意在清空file的value值)
                    $("#myupload")[0].reset();
                    $("#crop_container").html("");
                    $(".result").find("img").remove();
                    setTimeout(function () {
                        files.empty();
                    }, 1500);
                } else {
                    alert("数据异常,请刷新后重试！");
                }
            });
        });
        /**
         * 在inputfile外包含form表单,避免重复加载
         */
        if (!$("#fileuploadButton").parent().is("form#myupload")) {
            $("#fileuploadButton").wrap("<form id='myupload' action='" + _opt.postUrl + "' method='post' enctype='multipart/form-data'></form>");
        }
        this.reset_form();
        /**
         * 关闭文件选择框即失去焦点事件
         */
        document.getElementById("fileuploadButton").onpropertychange = this.file_blur;
        /**
         * 绑定上传按钮触发事件
         */
        /**
         * 绑定上传按钮触发事件
         */
        function uploadImage() {
            var last_img = $("#saveLastImgInfo").val();
            var last_crop_img = $("#saveLastCropImgInfo").val();
            $("#myupload").ajaxSubmit({
                dataType: 'json',
                data: {
                    act: "upload",
                    last_img: last_img,
                    last_crop_img: last_crop_img
                },
                beforeSend: function () {
                    btn.html("上传中...");
                    showimg.empty();
                    files.empty();
                    progress.show();
                    var percentVal = '0%';
                    bar.width(percentVal);
                    percent.html(percentVal);
                },
                uploadProgress: function (event, position, total, percentComplete) {
                    var percentVal = percentComplete + '%';
                    bar.width(percentVal);
                    percent.html(percentVal);
                },
                success: function (data) {
                    UploadCrop.img = _opt.imageUrl + data.pic;
                    UploadCrop.imgW = data.w;
                    UploadCrop.imgH = data.h;
                    UploadCrop.cropzoom = $('#crop_container').cropzoom({
                        width: containerWidth,//显示原始图片容器的宽度
                        height: containerHeight,//显示原始图片容器的高度
                        bgColor: '#CCC',
                        enableRotation: true,
                        enableZoom: true,
                        zoomSteps: 1,
                        rotationSteps: 90,
                        selector: {
                            w: _opt.cropMinWidth,
                            h: _opt.cropMinHeight,
                            maxWidth: _opt.cropMaxWidth,
                            maxHeight: _opt.cropMaxHeight,
                            centered: true,
                            borderColor: 'blue',
                            borderColorHover: 'red'
                        },
                        image: {
                            source: UploadCrop.img,
                            width: UploadCrop.imgW,
                            height: UploadCrop.imgH,
                            minZoom: 50,
                            maxZoom: 300
                        }
                    });
                    UploadCrop.cropzoom.setSelector(0, 0, _opt.cropMaxWidth, _opt.cropMaxHeight, true);
                    $("#crop_container_selector").css("position", "absolute");
                    $("#saveLastImgInfo").val(data.pic);
                    btn.html("上传图片");
                    $(".result").find("img").remove();
                    $("#myupload")[0].reset();
                    setTimeout(function () {
                        progress.hide();
                        $(".files").html("<b>" + data.name + "(" + data.size + "k)</b> <span class='delimg' id='delimgButton'>删除</span>");
                    }, 1000);
                },
                error: function (xhr) {
                    btn.html("上传失败");
                    bar.width(0)
                    files.html(xhr.responseText);
                    setTimeout(function () {
                        btn.html("重新上传");
                        $("#fileupload").val("");
                    }, 1000);
                }
            });
        }

        $("#fileuploadButton").change(uploadImage);
        /**
         * 确定按钮点击事件
         */
        $("#completeButton").click(function () {
            var id = $(this).attr("data-save");
            if (0 == $("#k").find("image").length) {
                alert("请选择要上传的图片！！");
                return;
            }
            if (0 == $(".result").find("img").length) {
                alert("请点击裁切按钮或关闭窗口！");
                return;
            }
            Dialog.confirm("确定后原始图片将被删除,确定继续吗？", function () {
                delete_image(_opt.complete.delNum, {
                    id: id
                }, function (data) {
                    _opt.complete.callback(data, id);
                    $('.result').find('.txt').show();
                });
                Dialog.close("updateImage");
                $("#mainDiv").remove();
            });
        });
        /**
         *删除图片 默认删除原图和裁切过的
         * 参数为1时只删除裁切过的
         */
        function delete_image(_n, _data, _fun) {
            var n = "undefined" == typeof(_n) ? 2 : _n;
            var fun = "undefined" == typeof(_fun) ? null : _fun;
            var last_img = $("#saveLastImgInfo").val();
            var last_crop_img = $("#saveLastCropImgInfo").val();
            //如果是点击
            var custom_img_url = UploadCrop.is_defined(_opt.custom_img_url) ? _opt.custom_img_url : "";
            if (last_img == custom_img_url) {
                n = 1;
            }
            alert(n);
            var data = {
                act: "delete",
                last_img: last_img,
                last_crop_img: last_crop_img
            };
            //为已知对象追加属性
            for (var data_attr in _data) {
                data[data_attr] = _data[data_attr];
            }
            switch (n) {
                case 1:
                    //不传递原图,只删除裁切过的
                    delete data.last_img;
                    break;
                case 2:
                    //原图和裁切过的一起传过去,全部删除
                    break;
                case 4:
                    //不传递裁切过的,只删除原图
                    delete data.last_crop_img;
                    break;
            }
            $.post(_opt.postUrl, data, fun);
        }
    }
};